package com.mazaiting.web.wrapper;

import com.alibaba.fastjson.JSON;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;

/**
 * 参数转换请求包装
 * JSON 数据转换
 */
public class HttpFormContentRequestWrapper extends HttpServletRequestWrapper {

    private final MultiValueMap<String, Object> formParameters;

    public HttpFormContentRequestWrapper(HttpServletRequest request, MultiValueMap<String, Object> parameters) {
        super(request);
        this.formParameters = (parameters != null) ? parameters : new LinkedMultiValueMap<>();
    }

    @Override
    public String getParameter(String name) {
        String queryStringValue = super.getParameter(name);
        if (StringUtils.hasLength(queryStringValue)) {
            return queryStringValue;
        }
        Object obj = this.formParameters.getFirst(name);
        if (Objects.nonNull(obj) && obj instanceof String value) {
            return value;
        }
        return JSON.toJSONString(obj);
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> result = new LinkedHashMap<String, String[]>();
        Enumeration<String> names = this.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            result.put(name, this.getParameterValues(name));
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Enumeration<String> getParameterNames() {
        Set<String> names = new LinkedHashSet<String>();
        names.addAll(Collections.list(super.getParameterNames()));
        names.addAll(this.formParameters.keySet());
        return Collections.enumeration(names);
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] queryStringValues = super.getParameterValues(name);
        // 查询数据
        List<Object> formValues = this.formParameters.get(name);
        List<String> result = new ArrayList<>();
        // 不为空则添加
        if (Objects.nonNull(queryStringValues)) {
            result.addAll(Arrays.asList(queryStringValues));
        }
        // 不为空则添加
        if (Objects.nonNull(formValues)) {
            result.addAll(formValues.stream().map(o -> o instanceof String v ? v : o.toString()).toList());
        }
        return result.toArray(new String[]{});
    }
}